package com.project.dubbo.springboot.starter.autoconfigure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.spring.AnnotationBean;

@Configuration
@EnableConfigurationProperties(DubboProperties.class)
@ConditionalOnClass({ AnnotationBean.class, ApplicationConfig.class, ProtocolConfig.class, RegistryConfig.class })
public class DubboAutoConfiguration {

	@Autowired
	private DubboProperties props;
	
	@Bean
	@ConditionalOnMissingBean(AnnotationBean.class)
	public AnnotationBean annotationBean(@Value("${dubbo.packageName}") String packageName) {
		AnnotationBean annotationBean = new AnnotationBean();
		annotationBean.setPackage(packageName);
		return annotationBean;
	}
	
	@Bean
	@ConditionalOnMissingBean(ApplicationConfig.class)
	public ApplicationConfig appplicationConfig() {
		ApplicationConfig applicationConfig = new ApplicationConfig();
		applicationConfig.setName(props.getApplication().getName());
		return applicationConfig;
	}
	
	@Bean
	@ConditionalOnMissingBean(ProtocolConfig.class)
	public ProtocolConfig protocolConfig() {
		ProtocolConfig protocolConfig = new ProtocolConfig();
		protocolConfig.setName(props.getProtocol().getName());
		protocolConfig.setPort(props.getProtocol().getPort());
		return protocolConfig;
	}
	
	@Bean
	@ConditionalOnMissingBean(RegistryConfig.class)
	public RegistryConfig registryConfig() {
		RegistryConfig registryConfig = new RegistryConfig();
		registryConfig.setAddress(props.getRegistry().getAddress());
		return registryConfig;
	}
	
}
